﻿namespace ExtPageBuilder
{
    using Ext.Net;
    using System.Linq;
    using System.Collections.Generic;
    using System;
    public partial class ExtCardPage : ExtPage
    {
        #region Properties
        private List<ExtPageBuilder.Object> _ObjectLines = new List<Object>();
        private DynamicExtControl _DyExt = new DynamicExtControl();
        private List<GridPanel> _GridLines = new List<GridPanel>();
        private int _LinePageSize = 15;
        public List<GridPanel> GridLines
        {
            get { return _GridLines; }
            set { _GridLines = value; }
        }
        private List<Panel> _PagePanels = new List<Panel>();

        public List<ExtPageBuilder.Object> ObjectLines
        {
            get { return _ObjectLines; }
            set { _ObjectLines = value; this.ObjectLinesChanged(); }
        }
        public List<Panel> PagePanels
        {
            get { return _PagePanels; }
            set { _PagePanels = value; }
        }
        #endregion Properties
        public ExtCardPage()
        {
            this.PageType = ExtPageType.Card;
        }
        public ExtCardPage(bool editable)
        {
            this.PageType = ExtPageType.Card;
            this.Editable = editable;
        }
        /// <summary>
        /// 
        /// </summary>
        protected void ObjectLinesChanged()
        {
            foreach (Object obj in this._ObjectLines)
            {
                if (GridLines.SingleOrDefault(g => g.ID == ("grdLine" + obj.ID)) == null)
                {
                    GridPanel g = this.BuilExtGridLine(obj);
                    this.GridLines.Add(g);
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        protected override void PageObjectChanged()
        {
            this.BuilPageStore();
            this.BuilPageForm();
        }
        public void BuilPageForm()
        {
            // Lấy thông tin List tab có trong 1 table, gôm nhóm những object có chung Tab_name.
            List<string> objectinfoTab_name = (from a in this._PageObject.Items
                                               orderby a.Form_tab_index
                                               select a.Tab_name).Distinct().ToList();

            for (int i = 0; i < objectinfoTab_name.Count; i++)
            {

                // Tạo Panel để chứa ColumnLayout, Panel này sẽ được add vào tabPanel truyền từ page giao diện xuống.
                Panel objPanel = new Panel(objectinfoTab_name[i] == null ? "" : objectinfoTab_name[i]);
                objPanel.ID = "Panel" + i.ToString();
                objPanel.IDMode = IDMode.Static;
                objPanel.Layout = "HBoxLayout";
                objPanel.Flex = 1;
                objPanel.AutoScroll = true;
                objPanel.Collapsible = true;
                objPanel.Border = false;
                objPanel.BodyBorder = 0;

                // Tạo FormLayout để chứa các control như TextField, DateField, v.v..
                List<FormPanel> FormPanelList = _DyExt.Buil_FormLayout(2, i);
                // objectinfoForFormLayout chứa thông tin các control được lấy từ DB mà cùng được đặt trong 1 Tab trên giao diện.
                List<Object_property> objectinfoForFormLayout = (from b in this._PageObject.Items
                                                                 where b.Tab_name == objectinfoTab_name[i]
                                                                 orderby b.Form_tab_index
                                                                 select b).ToList();

                // Biến countinform để điếm số lượng field trên 1 FormLayout.
                int countinform = (int)Math.Ceiling((double)objectinfoForFormLayout.Count / FormPanelList.Count);

                // Duyệt qua List layoutColumn để add các control vào FormLayout.

                // Duyệt qua List thông tin các control được lấy từ DB mà cùng được đặt trong 1 Tab trên giao diện.
                for (int z = 0; z < objectinfoForFormLayout.Count; z++)
                {
                    Object_property o = objectinfoForFormLayout[z];
                    if (o.Editable != null && o.Editable.Value == false)
                        o.Editable = false;
                    else
                        o.Editable = this.Editable;

                    Field _f = _DyExt.Buil_control(o, this.LanguageID, false); // Tạo field control tương ứng với kiểu của Object_info.
                    if (_f == null)
                        continue;
                    int j = z <= objectinfoForFormLayout.Count / 2 ? 0 : 1;
                    if (FormPanelList[j].Items.SingleOrDefault(a => a.ID == _f.ID) == null)
                    {
                        _DyExt.set_FieldWidth(o, _f);
                        FormPanelList[j].Items.Add(_f);
                    }
                }
                objPanel.Items.AddRange(FormPanelList.ToArray());
                this._PagePanels.Add(objPanel);
            }
        }
        public void BuilPageStore()
        {
            JsonReader jsonr = new JsonReader();

            this._PageStore = new Store();
            this._PageStore.ID = "stoCard";
            this._PageStore.IDMode = IDMode.Static;
            this._PageStore.RemoteSort = true;
            this._PageStore.RemotePaging = true;
            this._PageStore.RemoteFilter = true;
            this._PageStore.AutoLoad = true;
            Model md = new Model();
            this._PageStore.Model.Add(md);
            foreach (Object_property op in this.PageObject.Items)
            {
                if (op.PreKey != null && op.PreKey.Value == true)
                {
                    jsonr.IDProperty = op.Name;
                }
                ModelField _f = _DyExt.Buil_recordfield(op, this.LanguageID);
                if (_f == null)
                    continue;
                if (this._PageStore.Model[0].Fields.SingleOrDefault(f => f.Name == _f.Name) == null)
                    this._PageStore.Model[0].Fields.Add(_f);
            }
            AjaxProxy ajp = new AjaxProxy();
            ajp.Url = "Services/RemoteData.ashx";
            jsonr.Root = "data";
            jsonr.TotalProperty = "total";
            jsonr.SuccessProperty = "success";
            jsonr.MessageProperty = "message";
            ajp.Reader.Add(jsonr);

            JsonWriter jsonw = new JsonWriter();
            jsonw.Root = "data";
            jsonw.Encode = true;
            jsonw.WriteAllFields = false;
            ajp.Writer.Add(jsonw);

            this._PageStore.Proxy.Add(ajp);

            StoreParameter sp = new StoreParameter("action", "operation.action", ParameterMode.Raw);
            this._PageStore.SyncParameters.Add(sp);
            StoreParameter sp2 = new StoreParameter("ob", this._PageObject.ID.ToString(), ParameterMode.Value);
            this._PageStore.SyncParameters.Add(sp2);

            Parameter pr1 = new Parameter("ob", this._PageObject.ID.ToString(), ParameterMode.Value);
            this._PageStore.AutoLoadParams.Add(pr1);
            this._PageStore.Listeners.Refresh.Fn += "stoCardDataRefresh";
        }

        public Store BuilLineStore(ExtPageBuilder.Object obj)
        {
            Store sto = new Store();
            sto.ID = "stoLine" + obj.ID;
            sto.IDMode = IDMode.Static;
            Model md = new Model();
            sto.Model.Add(md);
            foreach (Object_property op in obj.Items)
            {
                ModelField _f = _DyExt.Buil_recordfield(op, this.LanguageID);
                if (_f == null)
                    continue;
                if (sto.Model[0].Fields.SingleOrDefault(f => f.Name == _f.Name) == null)
                    sto.Model[0].Fields.Add(_f);
            }
            AjaxProxy ajp = new AjaxProxy();
            ajp.Url = "Services/RemoteData.ashx";
            JsonReader jsonr = new JsonReader();
            jsonr.Root = "data";
            jsonr.TotalProperty = "total";
            jsonr.SuccessProperty = "success";
            jsonr.MessageProperty = "message";
            ajp.Reader.Add(jsonr);

            JsonWriter jsonw = new JsonWriter();
            jsonw.Root = "data";
            jsonw.Encode = true;
            jsonw.WriteAllFields = false;
            ajp.Writer.Add(jsonw);

            sto.Proxy.Add(ajp);
            JsonObject jsonOLine = JSON.Deserialize<JsonObject>(this._PageObject.Link_Condition);
            StoreParameter sp = new StoreParameter("action", "operation.action", ParameterMode.Raw);
            sto.SyncParameters.Add(sp);

            StoreParameter sp2 = new StoreParameter("ob", obj.ID.ToString(), ParameterMode.Value);
            sto.SyncParameters.Add(sp2);

            StoreParameter sp3 = new StoreParameter("link", jsonOLine[obj.ID.ToString()].ToString(), ParameterMode.Value);
            sto.SyncParameters.Add(sp3);

            StoreParameter sp4 = new StoreParameter("card", this._PageObject.ID.ToString(), ParameterMode.Value);
            sto.SyncParameters.Add(sp4);
            Parameter pr1 = new Parameter("ob", obj.ID.ToString(), ParameterMode.Value);
            Parameter pr2 = new Parameter("card", this._PageObject.ID.ToString(), ParameterMode.Value);
            Parameter pr3 = new Parameter("link", jsonOLine[obj.ID.ToString()].ToString(), ParameterMode.Value);
            sto.AutoLoadParams.Add(pr1);
            sto.AutoLoadParams.Add(pr2);
            sto.AutoLoadParams.Add(pr3);
            sto.PageSize = this._LinePageSize;
            return sto;
        }


        public GridPanel BuilExtGridLine(ExtPageBuilder.Object obj)
        {
            GridPanel grd = new GridPanel();
            grd.ID = "grdLine" + obj.ID;
            grd.Title = obj.Caption;
            grd.Collapsible = true;
            grd.CollapseMode = CollapseMode.Default;

            grd.IDMode = IDMode.Static;
            grd.BodyBorder = 0;
            grd.Border = false;
            //Editing
            if (this.Editable)
            {
                CellEditing ce = new CellEditing();
                grd.Plugins.Add(ce);

            }
            //Selection model
            if (this.Editable)
            {
                CellSelectionModel celSelect = new CellSelectionModel();
                grd.SelectionModel.Add(celSelect);
            }
            else
            {
                RowSelectionModel rowSelect = new RowSelectionModel();
                grd.SelectionModel.Add(rowSelect);
            }

            foreach (Object_property op in obj.Items)
            {
                ColumnBase _c = _DyExt.Buil_grid_column(op, this.LanguageID, this.Editable);
                if (_c == null)
                    continue;
                if (grd.ColumnModel.Columns.SingleOrDefault(c => c.ID == _c.ID) == null)
                {
                    grd.ColumnModel.Columns.Add(_c);
                }
            }
            PagingToolbar pagt = new PagingToolbar();
            pagt.DisplayInfo = true;
            grd.BottomBar.Add(pagt);
            grd.Store.Add(this.BuilLineStore(obj));
            return grd;
        }
    }
}
